//引入axios
import Axios from 'axios';

import { Loading , MessageBox } from 'element-ui';

import store from '@/store';

import { getToken } from '@/libs/appHead';

//ajax错误处理
var catchError = (error)=>{
  if (error.response) {
    switch (error.response.status) {
      case 400:
        MessageBox.confirm('当前登录状态已失效，需要重新登录，是否继续?', '温馨提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
          showClose:false
        }).then(() => {
          store.commit('clearLoginStatus',()=>{
            window.location.reload();
          });
        }).catch(() => {});
        break;
      case 302:
        MessageBox.confirm('当前登录状态已失效，需要重新登录，是否继续?', '温馨提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
          showClose:false
        }).then(() => {
          store.commit('clearLoginStatus',()=>{
            window.location.reload();
          });
        }).catch(() => {});
        break;
      case 404:
        MessageBox({
          type:'warning',
          title:'温馨提示',
          message:'当前请求的API接口不存在！'
        });
        break;
      default:
        MessageBox({
          type:'warning',
          title:'温馨提示',
          message:'系统发生了致命错误，请联系管理员！'
        });
        break;
    }
  }
  return Promise.reject(error);
}


var loadingInstance = null;

//全局ajax默认设置
const http = Axios.create({
  baseURL: store.state.sDomin,
  //timeout: 6000,
  responseType:'json',
  headers:{
    "Content-Type":"application/json;charset=UTF-8"
  },
  transformRequest:[function(data){
    //post请求必须进行转换,否则后台收不到参数
    return JSON.stringify(data);
  }],
});

//ajax请求拦截器全局配置
http.interceptors.request.use(
  config=>{
    //每次请求发起之前显示loadding
    loadingInstance = Loading.service({
      text:'loading...',
      background:'rgba(0,0,0,.3)'
    });

    //判断是否存在token，如果存在的话，则为每条ajax请求头添加token字段
    let _token = getToken();
    if (_token && _token.length) {
      config.headers.token = _token;
    }else{
      config.headers.token = '';
    }
    return config;
  },
  catchError
);

http.interceptors.response.use(
  response=>{
    //每次响应回来之后立即隐藏loadding
    loadingInstance.close();

    if(typeof(response.data)=='undefined'){
      return window.JSON.parse(response.request.responseText);
    }else{
      return response.data;
    }

  },
  catchError
);


export default {
  install:function(vm){
    vm.prototype.$http = http;
  }
}
